import 'package:flutter/material.dart';
import 'package:flutter/cupertino.dart';
import 'package:x3_base_core/x3_base_core.dart';
import 'package:x3_component_core/utils/base_component_utils.dart';

class BaseSelectWeekOfYear extends StatefulWidget {
  final int year;
  final int week;
  final Function(int year, int week) selected;

  const BaseSelectWeekOfYear({Key key, @required this.year, @required this.week, @required this.selected}) : super(key: key);

  @override
  _BaseSelectWeekOfYearState createState() => _BaseSelectWeekOfYearState();
}

class _BaseSelectWeekOfYearState extends State<BaseSelectWeekOfYear> {
  /// 滚动列表item的豪赌
  static final double itemHeight = 48;

  /// 系统颜色 黑 Color(0xff333333) 白：Color(0xffffffff) 黑白主题选中颜色为Color(0xFFFF004F)
  Color get systemColor => Theme.of(context).primaryColor == Colors.white ? Color(0xFF333333) : Theme.of(context).primaryColor;

  /// 当前选择的年份
  int currSelectedYear;

  /// 当前选择的周
  int currSelectedWeek;

  /// 当前日期
  DateTime get nowTime => DateTime.now();

  /// 年的索引
  int yearIndex;

  /// 周的索引
  int weekIndex;

  /// 控制器
  FixedExtentScrollController yearScrollController;
  FixedExtentScrollController weekScrollController;

  // 年数组
  List<int> yearList = [];

  // 周数组
  List<int> weekList = [];

  @override
  void initState() {
    super.initState();
    if (widget.year != null) currSelectedYear = widget.year;
    if (widget.week != null) currSelectedWeek = widget.week;
    if (currSelectedYear == null) currSelectedYear = nowTime.year;
    if (currSelectedWeek == null) currSelectedWeek = BaseDateUtil.weekOfYear(date: nowTime);
    setupData();
    initSelectedIndex();
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      padding: EdgeInsets.only(left: 16, right: 16, bottom: 8),
      child: Column(
        children: [
          buildHead(),
          BaseComponentUtils.buildHorizontalDivider(),
          Expanded(child: buildYearAndWeekPickerView()),
        ],
      ),
    );
  }

  Widget buildHead() {
    return Container(
      color: Colors.white,
      margin: EdgeInsets.symmetric(vertical: 4),
      height: 40,
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          InkWell(onTap: onCancelEvent, child: Text('取消', style: Theme.of(context).textTheme.bodyText2.copyWith(fontSize: 14))),
          Expanded(child: SizedBox()),
          InkWell(onTap: onConfirmEvent, child: Text('确认', style: Theme.of(context).textTheme.bodyText2.copyWith(fontSize: 14, color: systemColor, fontWeight: FontWeight.bold))),
        ],
      ),
    );
  }

  Widget buildYearAndWeekPickerView() {
    return Container(
      child: Row(
        children: <Widget>[
          Expanded(flex: 1, child: buildYearPickerView()),
          Expanded(flex: 2, child: buildWeekPickerView()),
        ],
      ),
    );
  }

  Widget buildYearPickerView() {
    return Container(
      child: CupertinoPicker(
        itemExtent: itemHeight,
        scrollController: yearScrollController,
        children: buildYearWidget(),
        looping: false,
        selectionOverlay: Container(
          width: double.infinity,
          height: itemHeight,
          decoration: BoxDecoration(border: Border(top: BorderSide(color: Color(0xFFEFEFEF)), bottom: BorderSide(color: Color(0xFFEFEFEF)))),
        ),
        onSelectedItemChanged: (index) {
          yearIndex = index;
          currSelectedYear = yearList[yearIndex];

          if (currSelectedYear == nowTime.year && weekIndex > BaseDateUtil.getWeeksThereAreInTheYear(currSelectedYear)) {
            weekIndex = BaseDateUtil.getWeeksThereAreInTheYear(currSelectedYear) - 1;
            weekScrollController.jumpToItem(weekIndex);
          }

          if (currSelectedYear == nowTime.year - 1) {
            // 当前月进度
            double monthOffset = weekScrollController.offset;
            // 由于切换后月份不更新，唯有滚动一点点距离才能刷新，所有有这行代码
            weekScrollController.jumpTo(monthOffset == 0.0 ? 0.01 : monthOffset - 0.01);
          }
          setState(() {});
        },
      ),
    );
  }

  Widget buildWeekPickerView() {
    return Container(
      child: CupertinoPicker(
        itemExtent: itemHeight,
        scrollController: weekScrollController,
        children: buildWeekWidget(),
        looping: false,
        selectionOverlay: Container(
          width: double.infinity,
          height: itemHeight,
          decoration: BoxDecoration(border: Border(top: BorderSide(color: Color(0xFFEFEFEF)), bottom: BorderSide(color: Color(0xFFEFEFEF)))),
        ),
        onSelectedItemChanged: (index) {
          weekIndex = index;
          currSelectedWeek = weekList[weekIndex];
          setState(() {});
        },
      ),
    );
  }

  List<Widget> buildYearWidget() {
    List<Widget> yearListWidget = []; //先建一个数组用于存放循环生成的widget
    for (var item in yearList) {
      yearListWidget.add(Center(child: Text('$item年', style: TextStyle(color: Colors.black87, fontSize: 16), maxLines: 1)));
    }

    return yearListWidget;
  }

  ///月Widget
  List<Widget> buildWeekWidget() {
    List<Widget> weekListWidget = []; //先建一个数组用于存放循环生成的widget
    // 当前选中的年对应的全部周
    List<int> alreadyWeekList = List.generate(BaseDateUtil.getWeeksThereAreInTheYear(currSelectedYear), (index) => index + 1);
    for (var item in alreadyWeekList) {
      // 该周对应的开始结束时间
      List<DateTime> startAndEndOfTheWeek = BaseDateUtil.getSomeWeek(currSelectedYear, item);
      String showText = '第$item周 ${BaseTransformUtil.format(startAndEndOfTheWeek[0].month)}月${BaseTransformUtil.format(startAndEndOfTheWeek[0].day)}日 - ${BaseTransformUtil.format(startAndEndOfTheWeek[1].month)}月${BaseTransformUtil.format(startAndEndOfTheWeek[1].day)}日';
      weekListWidget.add(Center(child: Text(showText, style: TextStyle(color: Colors.black87, fontSize: 16), maxLines: 1)));
    }

    return weekListWidget;
  }

  ///初始化数据
  void setupData() {
    for (int i = 1970; i <= DateTime.now().year; i++) {
      yearList.add(i);
    }
    int allWeek = BaseDateUtil.getWeeksThereAreInTheYear(currSelectedYear);
    for (int i = 1; i <= allWeek; i++) {
      weekList.add(i);
    }
  }

  /// 取消
  void onCancelEvent() {
    BaseRouterUtil.getInstance().pop();
  }

  /// 确认事件
  void onConfirmEvent() {
    widget.selected(currSelectedYear, currSelectedWeek);
    BaseRouterUtil.getInstance().pop();
  }

  ///初始化时间索引
  void initSelectedIndex() {
    final List uniqueYearList = Set.from(yearList).toList();
    final List uniqueMonthList = Set.from(weekList).toList();

    ///获取索引
    if (currSelectedYear != null && currSelectedWeek != null) {
      setState(() {
        yearIndex = uniqueYearList.indexOf(currSelectedYear);
        weekIndex = uniqueMonthList.indexOf(currSelectedWeek);
      });
    } else {
      ///没有传选中日期默认当前系统时间
      String year = DateTime.now().year.toString();
      String month = DateTime.now().month.toString();

      setState(() {
        yearIndex = uniqueYearList.indexOf(year);
        weekIndex = uniqueYearList.indexOf(month);
      });
    }

    yearScrollController = FixedExtentScrollController(initialItem: yearIndex);
    weekScrollController = FixedExtentScrollController(initialItem: weekIndex);
  }
}
